package com.linkage.jz.bankruptcy.fragment.Main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.LawDetailActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.adapter.LawListViewAdapter;
import com.linkage.jz.bankruptcy.bean.LawListInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.Divider;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.icu.text.DateTimePatternGenerator.DAY;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class DateCalcDaysFrgment extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_calcdays, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);

    }

    private  RelativeLayout re_stime,re_etime;
    private LinearLayout ll_calc_ret;
    private  TextView tv_stime,tv_etime,calc_month,calc_month_day,calc_week,calc_week_day,calc_day;
    private Button btn_calc,btn_reset;
    private int type =1;
    private void init(View view) {
        re_stime = (RelativeLayout) view.findViewById(R.id.re_stime);
        re_etime = (RelativeLayout) view.findViewById(R.id.re_etime);
        tv_stime = (TextView)view.findViewById(R.id.tv_stime);
        tv_etime = (TextView)view.findViewById(R.id.tv_etime);
        calc_month = (TextView)view.findViewById(R.id.calc_month);
        calc_week = (TextView)view.findViewById(R.id.calc_week);
        calc_day = (TextView)view.findViewById(R.id.calc_day);
        calc_month_day = (TextView)view.findViewById(R.id.calc_month_day);
        calc_week_day = (TextView)view.findViewById(R.id.calc_week_day);

        btn_reset = (Button)view.findViewById(R.id.btn_reset);
        ll_calc_ret = (LinearLayout)view.findViewById(R.id.ll_calc_ret);
        btn_calc = (Button)view.findViewById(R.id.btn_calc);

        btn_reset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                tv_stime.setText("");
                tv_etime.setText("");
                showSave();
                ll_calc_ret.setVisibility(View.GONE);
                btn_reset.setVisibility(View.GONE);
            }
        });
        re_etime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                type= 2;
                if(tv_etime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_etime.getText().toString());
                }

            }
        });
        re_stime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                type =1;
                if(tv_stime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_stime.getText().toString());
                }

            }
        });
        showSave();
        btn_calc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String sTime = tv_stime.getText().toString();
                String eTime = tv_etime.getText().toString();
                if("".equalsIgnoreCase(sTime) ||"请选择".equalsIgnoreCase(sTime))
                {
                    Toast.makeText(getActivity(),"请选择开始时间",Toast.LENGTH_LONG).show();
                    return;
                }
                if("".equalsIgnoreCase(eTime)||"请选择".equalsIgnoreCase(eTime))
                {
                    Toast.makeText(getActivity(),"请选择结束时间",Toast.LENGTH_LONG).show();
                    return;
                }

                if(getTimeCompareSize(sTime,eTime) == 1)
                {
                    Toast.makeText(getActivity(),"结束时间不能早于开始时间",Toast.LENGTH_LONG).show();
                    return;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


                try {

                    getDifferMonth(sTime, eTime);
                    getDifferWeek(sdf.parse(sTime), sdf.parse(eTime));
                    getTimeDistance(sdf.parse(sTime), sdf.parse(eTime));
                    ll_calc_ret.setVisibility(View.VISIBLE);
                    btn_reset.setVisibility(View.VISIBLE);
                }catch (Exception e)
                {
                    e.printStackTrace();
                }

//                String content = "<font color=\"#FE6026\">" + data + "</font>";
//                TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
//                tvContent.setText(Html.fromHtml(content));

            }
        });
    }

    private void showSave()
    {

        String str2 =  tv_stime.getText().toString().trim();
        String str3 =  tv_etime.getText().toString().trim();



        if(  !str2.equalsIgnoreCase("")
                &&  !str3.equalsIgnoreCase("")
                )


        {


            btn_calc.setClickable(true);
            btn_calc.setBackgroundResource((R.drawable.corner_btn));

        }else{
            btn_calc.setClickable(false);
            btn_calc.setBackgroundResource((R.drawable.corner_nosel_btn));
        }


    }



    public void setDate(String initdata){

                //通过自定义控件AlertDialog实现
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View view = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_dateshow, null);
                final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
                //设置日期简略显示 否则详细显示 包括:星期\周
                datePicker.setCalendarViewShown(false);
                //初始化当前日期
                 Calendar calendar = Calendar.getInstance();
                if("".equalsIgnoreCase(initdata)) {
                    calendar.setTimeInMillis(System.currentTimeMillis());

                }else{
                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date initdate = sdf.parse(initdata);
                        calendar.setTime(initdate);
                    }catch (Exception ex)
                    {
                        ex.printStackTrace();
                    }

                }
                datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH), null);
                //设置date布局
                builder.setView(view);
                builder.setTitle("设置日期信息");
                builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //日期格式
                        StringBuffer sb = new StringBuffer();
                        sb.append(String.format("%d-%02d-%02d",
                                datePicker.getYear(),
                                datePicker.getMonth() + 1,
                                datePicker.getDayOfMonth()));
//                        oplandate.setText(sb);
//                        //赋值后面闹钟使用
                        int mYear = datePicker.getYear();
                        int mMonth = datePicker.getMonth();
                        int mDay = datePicker.getDayOfMonth();
                        if(type ==1)
                        {
                            tv_stime.setText(sb.toString());
                        }else{
                            tv_etime.setText(sb.toString());
                        }
                        showSave();
                        dialog.cancel();
                    }
                });
                builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.create().show();
            }



    /**
     * 获取两个日期的月数差
     * @param fromDate
     * @param toDate
     * @return
     */
    public  long getDifferMonth(String fromDate, String toDate) {

        try {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(sdf.parse(fromDate));
        aft.setTime(sdf.parse(toDate));
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        long ret= Math.abs(month + result);


        int tmp1 = Integer.parseInt(toDate.substring(fromDate.length()-2,toDate.length()));
        int tmp2 = Integer.parseInt(toDate.substring(toDate.length()-2,toDate.length()));
        long day = 0;
            int i_year = aft.get(Calendar.YEAR);    //获取年
            int i_month = aft.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            int i_day_s = bef.get(Calendar.DAY_OF_MONTH) ;   //获取月份，0表示1月份
            int i_day_e = aft.get(Calendar.DAY_OF_MONTH) ;   //获取月份，0表示1月份

            if(i_day_e<i_day_s) {
                aft.add(Calendar.MONTH, -1);
                if(ret ==1)
                {
                    ret = 0;
                }
            }
        //如果结束时间大于
             i_year = aft.get(Calendar.YEAR);    //获取年
             i_month = aft.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            i_day_s = bef.get(Calendar.DAY_OF_MONTH) ;   //获取月份，0表示1月份
            String str_tmp = i_year+"-"+i_month+"-"+i_day_s;
            day = getTimeDistance(sdf.parse(str_tmp), sdf.parse(toDate));



//        String tmp = toDate.substring(0,toDate.length()-2)+"01";
//        long day2 = getTimeDistance(sdf.parse(fromDate),sdf.parse(tmp));


        calc_month.setText(ret  +"");
        calc_month_day.setText(day+"");
        return ret;
        }catch (Exception ex)
        {
            ex.printStackTrace();
            return 0;
        }

    }


    /**
     * 获取两个日期的周数差
     * @param startTime
     * @param endTime
     * @return
     */
    public  long getDifferWeek(Date startTime, Date endTime) {

        try {
//            Date startFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek(startTime); // 获取这天所在的周的第一天
//            Date endFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek(endTime);
//
//            Calendar startCalendar = Calendar.getInstance();
//            startCalendar.setTime(startFirstDayOfWeek);
//            Calendar endCalendar = Calendar.getInstance();
//            endCalendar.setTime(endFirstDayOfWeek);

            long dayOffset = getTimeDistance(startTime, endTime);

            long weekOffset = dayOffset / 7;
            long otherday = dayOffset % 7;
//        if(weekOffset>0)
//        {
            calc_week.setText(weekOffset + "");
            calc_week_day.setText( otherday + "");
//        }
            return weekOffset;
        }catch (Exception ex)
        {
            ex.printStackTrace();
            return  0l;
        }

    }


    /**
     * 获得两个日期间距多少天
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public  long getTimeDistance(Date beginDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(beginDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, fromCalendar.getMinimum(Calendar.HOUR_OF_DAY));
        fromCalendar.set(Calendar.MINUTE, fromCalendar.getMinimum(Calendar.MINUTE));
        fromCalendar.set(Calendar.SECOND, fromCalendar.getMinimum(Calendar.SECOND));
        fromCalendar.set(Calendar.MILLISECOND, fromCalendar.getMinimum(Calendar.MILLISECOND));

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, fromCalendar.getMinimum(Calendar.HOUR_OF_DAY));
        toCalendar.set(Calendar.MINUTE, fromCalendar.getMinimum(Calendar.MINUTE));
        toCalendar.set(Calendar.SECOND, fromCalendar.getMinimum(Calendar.SECOND));
        toCalendar.set(Calendar.MILLISECOND, fromCalendar.getMinimum(Calendar.MILLISECOND));

        long dayDistance = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
        dayDistance = Math.abs(dayDistance);
        calc_day.setText(dayDistance+"");
        return dayDistance;
    }



    public static int getTimeCompareSize(String startTime, String endTime){
        int i=0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime()<date1.getTime()){
                i= 1;
            }else if (date2.getTime()==date1.getTime()){
                i= 2;
            }else if (date2.getTime()>date1.getTime()){
                //正常情况下的逻辑操作.
                i= 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  i;
    }




}
